import React, { useEffect } from "react";
import { Button, Form, Input } from "antd";
import type { FormInstance } from "antd/es/form";
import ImgUpload from "@/components/img-upload";
import { Auth } from "@/guard/permission";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import { UserInfoType } from "@/types/user";
import { userUpdate } from "@/api/user";
import { initUserInfo } from "@/store/features/user";
import store2 from "store2";
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const Setting: React.FC = () => {
  const formRef = React.useRef<FormInstance>(null);
  const { userInfo } = useSelector((state: RootState) => state.user);
  const dispatch = useDispatch();
  const onFinish = (values: UserInfoType) => {
    console.log(values);
    let { objectId, sessionToken } = userInfo as UserInfoType;
    userUpdate(objectId, sessionToken, values).then((res) => {
      let uinfo = { ...userInfo, ...values };
      dispatch(initUserInfo(uinfo)); //更新状态机
      store2.set("react-admin-2302", uinfo);
    });
  };

  const onReset = () => {
    formRef.current?.resetFields();
  };

  useEffect(() => {
    if (userInfo) {
      formRef.current?.setFieldsValue(userInfo);
    }
  }, []);

  let Btn = Auth(
    <Button type="primary" htmlType="submit">
      确定
    </Button>,
    ["超级管理员"]
  );
  return (
    <Form {...layout} ref={formRef} name="control-ref" onFinish={onFinish}>
      <Form.Item name="username" label="用户账号" rules={[{ required: true }]}>
        <Input readOnly />
      </Form.Item>
      <Form.Item name="nickname" label="昵称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="avatar" label="头像" rules={[{ required: true }]}>
        <ImgUpload />
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Btn />
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
      </Form.Item>
    </Form>
  );
};

export default Setting;
